package com.cm.sys.framework.interceptor;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.cm.sys.framework.aop.NotCheckLogin;
import com.cm.sys.framework.application.ApiResponseCode;
import com.cm.sys.framework.execption.BusinessException;
import com.cm.sys.framework.utils.JwtUtils;
import com.cm.sys.system.entity.User;
import com.cm.sys.system.service.UserService;

/***
 * 访问拦截器
 * 
 * @author yxq18
 *
 */
@Component
public class TokenValidationInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(TokenValidationInterceptor.class);

    @Autowired
    private UserService userService;

    /*
     * 进入controller层之前拦截请求
     * 返回值：表示是否将当前的请求拦截下来  false：拦截请求，请求终止。true：请求不被拦截，继续执行
     * Object obj:表示被拦的请求的目标对象（controller中方法）
     */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws IOException {
        logger.info("--请求的路径-------" + request.getServletPath());
        logger.info("-------请求的方法----------" + request.getMethod());

        if (handler instanceof HandlerMethod) {
            HandlerMethod h = (HandlerMethod)handler;
            if (h.getMethodAnnotation(NotCheckLogin.class) != null) {
                return true;
            }

            // 获取用户登录时获得的 Token
            String userLoginToken = request.getHeader("X-Session-Token");
            User user = JwtUtils.validateToken(userLoginToken);

            User verifyUser = userService.verifyUser(user.getId(), user.getPassword());

            if (!StringUtils.isEmpty(verifyUser)) {
                String token = verifyUser.getToken();
                if ("0".equals(token) || StringUtils.isEmpty(token) || "''".equals(token)) {
                    throw new BusinessException(ApiResponseCode.TOKEN_DELETE.getCode(),
                        ApiResponseCode.TOKEN_DELETE.getMessage());
                }
                return true;
            } else {
                throw new BusinessException(ApiResponseCode.CODE_LOGIN.getCode(),
                    ApiResponseCode.CODE_LOGIN.getMessage());
            }

        }
        return true;

    }

    /*
     * 处理请求完成后视图渲染之前的处理操作
     * 通过ModelAndView参数改变显示的视图，或发往视图的方法
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView modelAndView) {

    }

    /*
     * 视图渲染之后的操作
     */
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
        throws Exception {

    }

}
